package cc.messcat.web.system;

import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.constant.CommonRedisConstant;
import cc.messcat.common.model.Pager;
import cc.messcat.common.model.ResponseBean;
import cc.messcat.common.util.BeanUtil;
import cc.messcat.common.util.LogUtil;
import cc.messcat.entity.fupin.PoorVillage;
import cc.messcat.entity.helpPerson.HelpPerson;
import cc.messcat.entity.helpUnits.HelpUnits;
import cc.messcat.entity.system.McUser;
import cc.messcat.log.OperationLog;
import cc.messcat.service.fupin.PoorVillageService;
import cc.messcat.service.helppeson.HelppesonService;
import cc.messcat.service.helpunits.HelpunitsService;
import cc.messcat.service.system.UserService;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 帮扶单位
 *
 * @author John
 */
@Controller
@RequestMapping("/helpu")
public class HelpunitsController {
	private static Logger log = LoggerFactory.getLogger(HelpunitsController.class);

    @Autowired
    public HelpunitsService helpunitsService;
    @Autowired
    public PoorVillageService poorVillageService;

    @Autowired
    public HelppesonService helppesonService;
    
    @Autowired
    public UserService userService;
    

    //查询
    /**
     * @author Eddie
     */
    @RequestMapping(value = "/findAllhelpunits2", method = RequestMethod.POST)
    @ResponseBody
    public Object findAllhelpunits(Integer pageNo, Integer pageSize, String Affiliation, String Unit_name, String work_telephone) throws Exception {
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        Pager pager = this.helpunitsService.getPage(pageNo, pageSize, Affiliation, Unit_name, work_telephone);
        //List<HelpUnits> resultList = helpunitsService.retrieveAllObjects();
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }

    //扶贫单位管理查询
    /**
     * @author Eddie
     */
//    @OperationLog(desc="扶贫单位管理查询",module="扶贫主体管理")
    @RequestMapping(value = "/findAllhelpunits", method = RequestMethod.POST)
    @ResponseBody
    public Object findAllhelpunits(Integer pageNo, Integer pageSize, HelpUnits helpUnits, String country,String cry,String unitName,HttpServletRequest req) throws Exception {
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        helpUnits.setCountry(StringUtils.isNotBlank(country) ? country : cry);
        helpUnits.setUnit_name(StringUtils.isNotBlank(unitName) ? unitName : helpUnits.getUnit_name());
        McUser user = (McUser)req.getSession().getAttribute("user");
        Pager pager = this.helpunitsService.listHelpUnit(pageNo, pageSize, helpUnits,user);
        //List<HelpUnits> resultList = helpunitsService.retrieveAllObjects();
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }


    //帮扶单位管理模糊查询
    /**
     * @author Eddie
     */
    @OperationLog(desc="帮扶单位管理模糊查询",module="扶贫主体管理")
    @RequestMapping(value = "/finhelpunits", method = RequestMethod.POST)
    @ResponseBody
    public Object finhelpunits(Integer pageNo, Integer pageSize, String Unit_name, String Contact_phone, String cty) throws Exception {
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        Pager pager = this.helpunitsService.getretrievePage(pageNo, pageSize, Unit_name, Contact_phone, cty);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, pager);
    }

    //根据id查出相对应的帮扶负责人
    /**
     * @author Eddie
     */
    @OperationLog(desc="根据id查出相对应的帮扶负责人",module="扶贫主体管理")
    @RequestMapping(value = "/findhelpunits", method = RequestMethod.POST)
    @ResponseBody
    public Object findhelpunits(Long id) throws Exception {
        List<HelpPerson> helpPerson = this.helppesonService.helpPerson(id);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, helpPerson);
    }

    //扶贫单位修改
    /**
     * @author Eddie
     */
    @OperationLog(desc="扶贫单位修改",module="扶贫主体管理")
    @RequestMapping(value = "/updatehelpunits", method = RequestMethod.POST)
    @ResponseBody
    public Object updatehelpunits(HelpUnits helpUnits) throws Exception {
    	SimpleDateFormat tempDate = new SimpleDateFormat("yyyy");
		String datetime = tempDate.format(new Date());
//		helpUnits.setAnnual(datetime);
        helpunitsService.modifyHelpu(helpUnits);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_UPDATE_SUCCESS, helpUnits);
    }

    //根据id修改
    /**
     * @author Eddie
     */
    @RequestMapping(value = "/updatehel", method = RequestMethod.POST)
    @ResponseBody
    public Object updatehel(@PathVariable Long id) throws Exception {
    	SimpleDateFormat tempDate = new SimpleDateFormat("yyyy");
		String datetime = tempDate.format(new Date());
        HelpUnits helpUnits = helpunitsService.retrieveObject(id);
//        helpUnits.setAnnual(datetime);
        helpunitsService.modifyHelpu(helpUnits);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_UPDATE_SUCCESS, id);
    }


    //添加扶贫单位
    @OperationLog(desc="扶贫单位添加",module="扶贫主体管理")
    @RequestMapping(value = "/addhelpunits", method = RequestMethod.POST)
    @ResponseBody
    public Object addhelpunits(HelpUnits helpUnits,String cty, String cry) throws Exception {
        //兼容操作
        if (BeanUtil.isValid(cty))
            helpUnits.setCounty(cty);
        if (BeanUtil.isValid(cry))
            helpUnits.setCountry(cry);
        helpunitsService.addHelpu(helpUnits);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_ADD_SUCCESS, helpUnits);
    }

    //扶贫单位删除
    @OperationLog(desc="扶贫单位删除",module="扶贫主体管理")
    @RequestMapping(value = "/delecthelpunits", method = RequestMethod.POST)
    @ResponseBody
    public Object delectarea(Long id) throws Exception {
    	HelpUnits hu = this.helpunitsService.retrieveObject(HelpUnits.class,id);
    	// XXX 20171130 帮扶单位有结对不能删除
    	boolean haveHP = false;
    	if(hu.getHelpPerson() != null) {
    		for(HelpPerson hp : hu.getHelpPerson()) {
    			if("1".equals(hp.getStatus())) {
    				haveHP = true;
    			}
    		}
    	}
    	if(!hu.getPoorVillages().isEmpty()) {
    		return  new ResponseBean(CommonConstant.SUCCESS_CODE_200, 
    			haveHP ? "该帮扶单位已结对并且已关联帮扶责任人，无法删除" : "该帮扶单位已结对，无法删除"
    			, "failure");
    	}
    	if(haveHP) {
    		return  new ResponseBean(CommonConstant.SUCCESS_CODE_200, "该帮扶单位已关联帮扶责任人，无法删除","failure");
    	}
    	helpunitsService.removeHelpu(id);
    	//end

        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_DELETE_SUCCESS, id);
    }


    //根据id查询帮扶负责人修改
    @OperationLog(desc="根据id查询帮扶负责人修改",module="扶贫主体管理")
    @RequestMapping(value = "/gethelpunits", method = RequestMethod.POST)
    @ResponseBody
    public Object gethelpunits(Long id) throws Exception {
    	SimpleDateFormat tempDate = new SimpleDateFormat("yyyy");
		String datetime = tempDate.format(new Date());
        PoorVillage poorVillage = poorVillageService.retrieveObject(id);
        poorVillage.setAnnual(poorVillage.getAnnual());
        poorVillageService.modifyPoorVillages(poorVillage);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_UPDATE_SUCCESS, poorVillage);
    }


    //根据ID查询
    @RequestMapping(value = "/gethelpunitById", method = RequestMethod.POST)
    @ResponseBody
    public Object gethelpunitById(Long id) throws Exception {
        if (id == null) {
            return null;
        }
        HelpUnits helpUnits = helpunitsService.retrieveObject(id);
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, helpUnits);
    }

  	
  	//扶贫单位修改
    @OperationLog(desc="帮扶单位修改",module="扶贫主体管理")
  	@RequestMapping(value = "/updatehu", method = RequestMethod.POST)
  	@ResponseBody
  	public Object updatehelpunitsNew(HelpUnits helpUnits)throws Exception{
  		helpunitsService.modifyHelpuNew(helpUnits);
  		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_UPDATE_SUCCESS,null);
  	}
  	
  	
  	
  	/**
  	 * 帮扶单位导入
  	 * @param file
  	 * @param session
  	 * @return
  	 */
    @OperationLog(desc = "帮扶单位导入", module = "扶贫主体管理")
	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	@ResponseBody
	public Object addHelpUnitsExc(String file, HttpSession session) {
		long dataTimeS = System.currentTimeMillis();
		try {
			McUser mcUser = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
			// 开始导入
			String result = this.helpunitsService.adduploadFile(file, session, mcUser);
			
			long dataTimeE = System.currentTimeMillis();
			log.info(dataTimeE-dataTimeS+"S>>>>>>>>>>>>>>>扶贫单位导入总耗时");
			// 路径
			if ("NO_URL".equals(result)) {
				return new ResponseBean(CommonConstant.FAIL_CODE_400, CommonConstant.MSG_FILE_NOURL);
			}
			// 导入错误
			if (!"T".equals(result)) {
				return new ResponseBean(CommonConstant.SUCCESS_CODE_300, CommonConstant.MSG_IMPORT_ERROR, result);
			}
			return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_IMPORT_SUCCESS);
		} catch (Exception e) {
			LogUtil.logException("HelpunitsController import has exception:", e);
			e.printStackTrace();
			return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_IMPORT_ERROR);
		}
	}
  	
  	
  	
}
